package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author songyi
 * @date 2020/6/28 0028 14:54
 * @description 封装响应信息，需要依赖OutputStream
 */
public class Response {

    private OutputStream outputStream;

    public Response() {
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /**
     * 1.根据url获取到静态资源的绝对路径
     * 2.根据绝对路径读取该静态资源文件
     * 3.最终通过输出流输出
     */
    public void outputHtml(Request request, Mapper mapper) throws IOException {
        String appBase = mapper.getHostMap().get(request.getHost()).getAppBase();
        // String absoluteResourcePath = StaticResourceUtil.getAbsolutePath(url);
        File file = new File(appBase + request.getUrl());
        if (file.exists() && file.isFile()) {
            // 输出静态资源
            StaticResourceUtil.outputStaticResource(new FileInputStream(file), outputStream);
        } else {
            // 输出404
            output(HttpProtocoUtil.getHeader404());
        }
    }

    // 输出指定字符串
    public void output(String content) throws IOException {
        outputStream.write(content.getBytes());
    }
}
